package com.nehc.nettyserver.config;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Netty配置类 - 集成JDK 21虚拟线程
 * 
 * @author NEHC
 * @date 2023-04-02
 */
@Configuration
public class NettyConfig {

    @Value("${netty.server.boss-threads:1}")
    private int bossThreads;

    @Value("${netty.server.worker-threads:0}")
    private int workerThreads;

    /**
     * 使用JDK 21虚拟线程工厂
     */
    private ThreadFactory createVirtualThreadFactory(String namePattern) {
        return task -> {
            Thread.Builder.OfVirtual builder = Thread.ofVirtual();
            return builder.name(namePattern.formatted(Thread.currentThread().getThreadGroup().getName()))
                    .factory()
                    .newThread(task);
        };
    }

    /**
     * 配置Netty的Boss线程组
     * 负责接收连接，可以用少量普通线程
     */
    @Bean
    public EventLoopGroup bossGroup() {
        ThreadFactory threadFactory = new DefaultThreadFactory("netty-boss");
        return new DefaultEventLoopGroup(bossThreads, threadFactory);
    }

    /**
     * 配置Netty的Worker线程组
     * 负责IO操作，使用虚拟线程提高并发能力
     * workerThreads为0时表示使用系统默认的处理器数量
     */
    @Bean
    public EventLoopGroup workerGroup() {
        ThreadFactory threadFactory = createVirtualThreadFactory("netty-worker-%s");
        return new DefaultEventLoopGroup(workerThreads, threadFactory);
    }

    /**
     * 配置业务处理线程组
     * 使用虚拟线程处理业务逻辑
     */
    @Bean
    public EventLoopGroup businessGroup() {
        ThreadFactory threadFactory = createVirtualThreadFactory("netty-business-%s");
        return new DefaultEventLoopGroup(0, threadFactory);
    }
} 